<?php


use Monolog\Handler\StreamHandler;
use Monolog\Logger;

/**
 * Author:JunSong
 * CreatedTime: 2021/4/2 18:08
 */


class Http
{
    public $request = null;
    public $CONTROLLER;
    public static $container;
    public static $dispatcher;

    public function __construct()
    {
        $this->CONTROLLER = APPLICATION."/Controller/";
        $this->contianer = [];
        self::$dispatcher =  FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
            $r->get('/',[\app\Controller\BaseController::class,'test']);
        });
    }

    public function setRequest($request)
    {
        if(!$this->request){
            $this->request = $request;
        }
    }

    public function response(){

        $httpMethod = $this->request->server['request_method'];
        $uri = $this->request->server['request_uri'];
        $routeInfo = self::$dispatcher->dispatch($httpMethod,$uri);
        switch ($routeInfo[0]) {
            case FastRoute\Dispatcher::NOT_FOUND:
                // ... 404 Not Found
                return "404 Not Found";
            case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
                $allowedMethods = $routeInfo[1];
                // ... 405 Method Not Allowed
                return "405 Method Not Allowed:{$allowedMethods}";
            case FastRoute\Dispatcher::FOUND:
                $handler = $routeInfo[1];
                break;
        }
        $class = self::make($handler[0]);
        $method = $handler[1];
        $res = $class->$method();
        return json_encode($res,320);
    }

    /**
     * 请求日志记录
     * @param $req
     */
    public static function requestInfoLog($req){
        $log = new \Monolog\Logger('logs');
        $log->pushHandler(new StreamHandler(APP_PATH.'/runtime/logs/'.date('Ymd').'.log', Logger::INFO));
        $log->info(var_export($req,true));
    }

    public static function make($class)
    {
        if(!isset(self::$container[$class])){
            self::$container[$class] = new $class();
        }
        return self::$container[$class];
    }
}